CSS Background
CSS background property is used to define background effects on an element.
There are five CSS background properties that affect HTML elements:
- Background-color
- Background-image
- Background-repeat
- Background-attachment
- Background-position
CSS Background-color
The background-color property is used to define an element's background color.
You can set the background color as follows:
<!DOCTYPE html>
<html>
<head>
<style>
h2, p {
background-color: #b0d4de;
}
</style>
</head>
<body>
<h2>My first CSS page.</h2>
<p>Example of the CSS `background-color` property.</p>
</body>
</html>
Output
CSS Background-image
The background-image property is used to set an image as the background of an element. By default, the image covers the entire element.
You can set a background image for a page as follows:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("paper1.gif");
margin-left: 100px;
}
</style>
</head>
<body>
<h1>HEADING</h1>
</body>
</html>
Note: The background image should be selected to complement the text color. A poor combination of text and background image can result in a poorly designed and difficult-to-read webpage.
CSS Background-repeat
By default, the background-image property repeats the background image both horizontally and vertically. However, some images are repeated only horizontally or vertically.
The background often looks better when the image is repeated horizontally only.
Background-repeat:repeat-x;
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("img.png");
background-repeat: repeat-x;
}
</style>
</head>
<body>
<h1>HEADING</h1>
</body>
</html>
Background-repeat:repeat-y;
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("img.png");
background-repeat: repeat-y;
}
</style>
</head>
<body>
<h1>HEADING</h1>
</body>
</html>
CSS Background-attachment
The background-attachment property determines whether the background image is fixed or scrolls with the rest of the page in the browser window. If you set the background image to "fixed," it will remain stationary while the rest of the page scrolls.
Here's an example with a fixed background image:
background: white url('ab.gif') no-repeat fixed;
CSS Background-position
The background-position property sets the initial position of the background image. By default, the image is placed in the top-left corner of the webpage.
You can set the following positions:
- Center
- Top
- Bottom
- Left
- Right